import React from 'react';
import { history } from 'umi';
import { Card, Space, Button, Row, Col, message} from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import EditForm from './components/EditForm';
import {update, detail} from '@/services/Budget';

class Modify extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      unitId: null
    }
    this.id = props.location.query.id;
    this.formRef = React.createRef();
  }

  /* 重置 */
  onReset = () => {
    const {resetFields} = this.formRef.current;
    resetFields();
  }

  /* 获取详情 */
  getDetail = async () => {
    try {
      const id = this.id;
      const {setFieldsValue} = this.formRef.current;
      if (!id) throw new Error('非法请求');
      const res = await detail(id);
      const {unitId, benefitUnitId, code, sourceType, amount, parentBudgetId, remark} = res;
      setFieldsValue({
        benefitUnitId,
        code,
        sourceType,
        amount,
        parentBudgetId,
        remark
      })
      this.setState({unitId})
    } catch (e) {
      console.error('Budget.modify', e);
      e.message ? message.error(e.message) : null;
    }
  }

  /* 确认 */
  onConfirm = async () => {
    try {
      const id = this.id;
      const props = this.props;
      if (!id) throw new Error('非法请求');
      const {validateFields} = this.formRef.current;
      const values = await validateFields();
      this.setState({isLoading: true});
      await update({...values, id});
      message.success('修改成功');
      props.update ? props.update() : null;
      setTimeout(function() {history.goBack()}, 1500)
    } catch (e) {
      console.error('Budget.modify', e);
      e.message ? message.error(e.message) : null;
    } finally {
      this.setState({isLoading: false});
    }
  }

  componentDidMount () {
    this.getDetail();
  }

  render() {
    const {isLoading, unitId} = this.state;
    const {onConfirm, onReset, formRef} = this;
    return (
      <PageContainer>
        <Card
          style={{ paddingBottom: 24, borderBottom: 1 }}
          headStyle={{ borderBottom: "none" }}
          bodyStyle={{ paddingTop: 0, paddingBottom: 0 }}
          title="修改内容"
          bordered={false}>
          <div style={{ width: '70vw' }}>
            <EditForm id={unitId} ref={formRef}/>
            <Row>
              <Col span={6}></Col>
              <Col span={6}>
                <Space>
                  <Button onClick={() => {history.goBack()}}>取消</Button>
                  <Button onClick={onReset}>重置</Button>
                  <Button loading={isLoading} type="primary" onClick={onConfirm}>确定</Button>
                </Space>
              </Col>
            </Row>
          </div>
        </Card>
      </PageContainer>
    )
  }
}

export default Modify